package com.framework.base.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import net.spy.memcached.MemcachedClient;

import org.apache.log4j.Logger;

public class MemCacheUtil {
	public static Properties cacheProperties;
	static Logger logger=Logger.getLogger(MemCacheUtil.class);
	private static MemcachedClient mc=null;
	public static String ip ="";
	public static int port =11211;
	public static int cacheTime=31536000; //设置缓存时间
	public static Map<String,Object> cacheMap=new HashMap<String, Object>();
	public static boolean bool=false;
	static{
		if("".equals(ip)){
			cacheProperties = new Properties();
			try {
				cacheProperties.load(SysConfUtil.class
						.getResourceAsStream("/cache.properties"));
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			ip=cacheProperties.getProperty("ip");
			port=Integer.parseInt(cacheProperties.getProperty("port"));
		}
	}
	@SuppressWarnings({ "unused", "rawtypes" })
	public static void saveObject(String key, Object value) {
		try {
			if(bool){
				logger.info("memcache缓存ip="+ip+" 端口port="+port);
				/* 建立MemcachedClient 实例，并指定memcached服务的IP地址和端口号 */
				if(mc==null){
					mc = new MemcachedClient(new InetSocketAddress(ip, port));
				}
				Map<SocketAddress, Map<String, String>> stats = mc.getStats();
				Map<String,String> infoMap=stats.get(new InetSocketAddress(ip, port));
				if(infoMap.keySet().size()==0){
					mc.shutdown(); //连接不成功，则关闭
					throw new Exception();
				}
				java.util.concurrent.Future<Boolean> b = null;
				/* 将key值，过期时间(秒)和要缓存的对象set到memcached中 */
				b = mc.set(key, cacheTime, value);
			}
		} catch (Exception ex) {
			bool=false;
			LoggerUtil.logError(ex,logger,"缓存服务器连接失败");
			ex.printStackTrace();
			
		}  
		if(!bool){
			cacheMap.put(key, value);
		}
	}

	public static Object readObject(String key) {
		 
		try {
			if(bool){
				logger.info("memcache缓存ip="+ip+" 端口port="+port);
				/* 建立MemcachedClient 实例，并指定memcached服务的IP地址和端口号 */
				if(mc==null){
					mc = new MemcachedClient(new InetSocketAddress(ip, port));
				}
				/* 按照key值从memcached中查找缓存，不存在则返回null */
				Object b = mc.get(key);
				return b;
			}else{
				return cacheMap.get(key);
			}
		} catch (Exception ex) {
			LoggerUtil.logError(ex,logger,"缓存服务器连接失败");
			ex.printStackTrace();
		}  
		return null;
	}
	
	public static Object deleteObject(String key) {
		 
		if(bool){
			try {
				logger.info("memcache缓存ip="+ip+" 端口port="+port+" key="+key);
				/* 按照key值从memcached中查找缓存，不存在则返回null */
				Object b = mc.delete(key);
				return b;
			} catch (Exception ex) {
				LoggerUtil.logError(ex,logger,"缓存服务器连接失败");
				ex.printStackTrace();
			}  
		}else{
			return cacheMap.remove(key);
		}
		return null;
	}
}
